package com.lc.zpyh.ui.activity;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.lc.zpyh.R;
import com.lc.zpyh.app.AppActivity;
import com.lc.zpyh.http.request.DelCarApi;
import com.lc.zpyh.http.request.SchoolApi;
import com.lc.zpyh.http.request.SelectToBeConfirmedApi;
import com.lc.zpyh.http.response.CarBean;
import com.lc.zpyh.http.response.SchoolBean;
import com.lc.zpyh.http.response.SelectToBeConfirmedBean;
import com.lc.zpyh.other.IntentKey;
import com.lc.zpyh.ui.activity.supermarket.ConfirmOrderActivity;
import com.lc.zpyh.ui.fragment.shopcar.ShopCarFragment;
import com.lc.zpyh.util.BigDecimalUtils;
import com.lc.zpyh.util.SPUtil;
import com.lc.zpyh.util.constant.EvenConstant;
import com.lc.zpyh.util.eventbus.Event;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

/**
 *    author : Android 轮胎哥
 *    github : https://github.com/getActivity/AndroidProject
 *    time   : 2018/10/18分
 *    desc   : 购物车
 */
public final class ShopCarActivity extends AppActivity implements ShopCarFragment.CallBackCommitValue, View.OnClickListener {
    ViewPager viewPager;
    private TabLayout mTabTl;
    private List<Fragment> tabFragments = new ArrayList<>();//碎片集合
    private List<String> tabIndicators = new ArrayList<>();//title集合
    private List<String> ids = new ArrayList<>();
    TitleBar titleBar;
    TextView checkTv;
    private CheckBox checkBox;
    private TextView totleTv;
    private TextView psTv;
    private List<String> cartIds =new ArrayList<>();

    private ContentPagerAdapter contentAdapter;
    @Override
    protected int getLayoutId() {
        return R.layout.shop_car_activity;
    }

    @Override
    protected void initView() {
        mTabTl = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewpager);
        checkTv = findViewById(R.id.check_tv);
        checkTv.setOnClickListener(this);
        checkBox = findViewById(R.id.item_check);
        titleBar = findViewById(R.id.top);
        totleTv= findViewById(R.id.sum_price);
        psTv= findViewById(R.id.ps_tv);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                    finish();
            }

            @Override
            public void onTitleClick(View v) {

            }

            @Override
            public void onRightClick(View v) {
                ShopCarFragment fragment= (ShopCarFragment) contentAdapter.getItem(cur_poi);
                if(titleBar.getRightTitle().equals("管理")){
                    titleBar.setRightTitle("完成");
                    checkTv.setText("删除");
                    fragment.setCheckTv(checkTv.getText().toString());
                    checkTv.setBackgroundColor(Color.parseColor("#d83b31"));
                }else {
                    titleBar.setRightTitle("管理");
                    checkTv.setText("去结算");
                    fragment.setCheckTv(checkTv.getText().toString());
                    if(ss.size()>0){
                        checkTv.setBackgroundColor(Color.parseColor("#E46006"));
                    }else {
                        checkTv.setBackgroundColor(Color.parseColor("#999999"));
                    }
                }
            }
        });
        checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ShopCarFragment fragment= (ShopCarFragment) contentAdapter.getItem(cur_poi);
                //通过checkbox的isChecked()方法判断是否选中、
                boolean checked = checkBox.isChecked();
                if(checked){
                    fragment.checkAll(checkTv.getText().toString());
                }else {
                    fragment.notAll();
                }
            }
        });
    }
    private int cur_poi=0;
    @Override
    protected void initData() {
        getShoolById();
        mTabTl.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                cur_poi = tab.getPosition();
                checkBox.setChecked(false);
                ShopCarFragment fragment= (ShopCarFragment) contentAdapter.getItem(tab.getPosition());
                fragment.showMessageFromActivity(ids.get(tab.getPosition()),checkTv.getText().toString());
                totleTv.setText("￥"+0);
                psTv.setText("不含配送费");
                checkTv.setBackgroundColor(Color.parseColor("#999999"));
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }
   private void getShoolById(){
        EasyHttp.post(this).api(new SchoolApi().setSchoolId(SPUtil.get(this,IntentKey.ADDRESSID,""))).request(new HttpCallback<SchoolBean>(this) {
                @Override
                public void onSucceed(SchoolBean data) {
                    //全部单独添加
                    tabIndicators.add("全部");
                    tabFragments.add(ShopCarFragment.newInstance("",checkTv.getText().toString()));
                    ids.add("");
                    //其余食堂id
                    for(SchoolBean.ListDTO dto :data.getList()){
                        tabIndicators.add(dto.getName());
                        tabFragments.add(ShopCarFragment.newInstance(dto.getId(),checkTv.getText().toString()));
                        ids.add(dto.getId()+"");
                    }
                    contentAdapter = new ContentPagerAdapter(getSupportFragmentManager());
                    viewPager.setAdapter(contentAdapter);
                    viewPager.setOffscreenPageLimit(1);
                    mTabTl.setTabMode(TabLayout.MODE_SCROLLABLE);
                    mTabTl.setTabRippleColor(ColorStateList.valueOf(Color.parseColor("#00000000")));
                    mTabTl.setupWithViewPager(viewPager);
                }
                @Override
                public void onFail(Exception e) {
                    super.onFail(e);
                }
          });
    }
    private void delCarById(String id){
        EasyHttp.post(this).api(new DelCarApi().setIds(id)).request(new HttpCallback<SchoolBean>(this) {
            @Override
            public void onSucceed(SchoolBean data) {
                if(data.getCode()==0){
                    ShopCarFragment fragment= (ShopCarFragment) contentAdapter.getItem(cur_poi);
                    fragment.showMessageFromActivity(ids.get(cur_poi),checkTv.getText().toString());
                }
            }
            @Override
            public void onFail(Exception e) {
                super.onFail(e);
            }
        });
    }
     private boolean hasCheck=false;
     private int totalMoney = 0;
     //装食堂id 的数组
     private List<String> ss = new ArrayList<String>();
     private CarBean new_car;
    @Override
    public void SendMoney(CarBean car) {
        new_car =car;
        totalMoney = 0;

        ss.clear();
        for(int i = 0;i<car.getList().size();i++){
            CarBean.ListDTO listDTO =car.getList().get(i);
            if(listDTO.isAll()){
                ss.add(listDTO.getCanteenId());
            }
            hasCheck = false;
           for(int j=0;j< listDTO.getCarts().size();j++){
               CarBean.CartsDTO cartsDTO =listDTO.getCarts().get(j);
               if(!listDTO.isAll() && !hasCheck){
                   if(cartsDTO.isAll()){
                       ss.add(listDTO.getCanteenId());
                       hasCheck =true;
                   }
               }
               if(cartsDTO.isAll()){
                   if(cartsDTO.getSpecificationId()==null){
                       if (cartsDTO.getPrice()==null){
                           totalMoney +=cartsDTO.getSpjg()*cartsDTO.getCount();
                       }else {
                           totalMoney +=cartsDTO.getPrice()*cartsDTO.getCount();
                       }

                   }else {
                       if (cartsDTO.getGgzjg()!=null){
                           totalMoney +=cartsDTO.getGgzjg()*cartsDTO.getCount();
                       }else {
                           if (cartsDTO.getPrice()!=null){
                               totalMoney +=cartsDTO.getPrice()*cartsDTO.getCount();
                           }else {

                           if (cartsDTO.getSpjg()!=null){
                               totalMoney +=cartsDTO.getSpjg()*cartsDTO.getCount();
                           }else {
                               totalMoney +=cartsDTO.getSpyjg()*cartsDTO.getCount();
                           }
                           }
                       }
                   }
               }
            }
        }
        // 食堂id数据去重
        Set set = new HashSet();
        set.addAll(ss);
        ss.clear();
        ss.addAll(set);
        totleTv.setText("￥"+(Double.parseDouble(BigDecimalUtils.div(totalMoney+"","100",2)+"")));
//        +ss.size()*5
        if(ss.size() == 0){
            psTv.setText("不含配送费");
            checkTv.setBackgroundColor(Color.parseColor("#999999"));
        }else {
            psTv.setText("配送费："+ss.size()*5+"元");
            checkTv.setBackgroundColor(Color.parseColor("#E46006"));
        }
    }

    @Override
    public void SelectAll(boolean state) {
        checkBox.setChecked(state);
    }

    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.check_tv:
                if( checkTv.getText().toString().equals("删除")){
                    //删除接口
                    if(new_car!=null){
                       for(int i=0;i<new_car.getList().size();i++){
                            CarBean.ListDTO listDTO = new_car.getList().get(i);
                            for(int j=0;j<listDTO.getCarts().size();j++){
                                CarBean.CartsDTO cartsDTO =listDTO.getCarts().get(j);
                                if(cartsDTO.isAll()){
                                    //listDTO.getCarts().remove(cartsDTO);
                                    cartIds.add(cartsDTO.getCartId()+"");
                                }
                            }
                       }
                        if (cartIds.size()>0) {
                            StringBuffer sb = new StringBuffer();
                            for (String str : cartIds) {
                                sb.append(str).append(",");
                            }
                            String carids = sb.deleteCharAt(sb.length() - 1).toString();
                            delCarById(carids);
                            cartIds.clear();
                        }else {
                            toast("请选择商品");
                        }
                    }
                }else {
                    //去结算
                    //这这里调用接口
                    if(new_car!=null) {
                        for (int i = 0; i < new_car.getList().size(); i++) {
                            CarBean.ListDTO listDTO = new_car.getList().get(i);
                            for (int j = 0; j < listDTO.getCarts().size(); j++) {
                                CarBean.CartsDTO cartsDTO = listDTO.getCarts().get(j);
                                if (cartsDTO.isAll()) {
                                    //listDTO.getCarts().remove(cartsDTO);
                                    cartIds.add(cartsDTO.getCartId() + "");
                                }
                            }
                        }
                        if (cartIds.size()>0) {
                            StringBuffer sb = new StringBuffer();
                            for (String str : cartIds) {
                                sb.append(str).append(",");
                            }
                            String carids = sb.deleteCharAt(sb.length() - 1).toString();
                            selectToBeConfirmed(carids);
                            cartIds.clear();
                        }else {
                            toast("请选择商品");
                        }
                    }

                }
                break;
        }
    }

    private void selectToBeConfirmed(String carids) {
        Log.e("@@@@", "selectToBeConfirmed: "+carids );
            EasyHttp.post(this)
                    .api(new SelectToBeConfirmedApi().setUserid(SPUtil.get(this, IntentKey.USERID, "")).setCartIds(carids).setSchoolId(SPUtil.get(this,IntentKey.ADDRESSID,""))).request(new HttpCallback<SelectToBeConfirmedBean>(this) {

                @Override
                public void onSucceed(SelectToBeConfirmedBean data) {
                    if (data.getCode() == 0) {
                        startActivity(new Intent(ShopCarActivity.this, ConfirmOrderActivity.class).putExtra("orderList", data.getList()).putExtra("cartIds",carids));
                    }
                }

                @Override
                public void onFail(Exception e) {
                    super.onFail(e);

                }
            });
    }


    class ContentPagerAdapter extends FragmentPagerAdapter{

        public ContentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return tabFragments.get(position);
        }

        @Override
        public int getCount() {
            return tabIndicators.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabIndicators.get(position);
        }
    }
    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }

    @Override
    protected void receiveEvent(Event event) {
        super.receiveEvent(event);
        if (event.getCode()== EvenConstant.PAYSTAUTS){
            finish();
        }
    }
}